package com.space.user.service;

import com.space.client.api.AccountServiceI;
import com.space.client.domainevent.CreateUserAccountEvent;
import com.space.client.dto.ModifyUserInfoCommand;
import com.space.client.api.UserInfoServiceI;
import com.space.client.dto.UserAccountInfoDTO;
import com.space.user.assembler.UserInfoAssembler;
import com.space.user.domain.info.entity.UserInfo;
import com.space.user.domain.info.service.UserInfoDomainService;
import com.space.client.dto.UserInfoDTO;
import com.space.user.domain.info.valueobject.Account;
import com.space.user.domain.info.valueobject.Nickname;
import com.space.user.domain.info.valueobject.UserId;
import com.space.user.mq.DomainEventBus;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

/**
 * @author <a href="mailto:414563035@qq.com">Bedroom</a>
 * @date 2021/4/13 5:15 下午
 */
@DubboService
@Service
@Validated
public class UserInfoServiceImpl implements UserInfoServiceI {
    @Autowired
    private UserInfoDomainService userInfoDomainService;

    @Resource
    private AccountServiceI accountService;

    @Autowired
    private UserInfoAssembler userInfoAssembler;

    @Autowired
    private DomainEventBus domainEventBus;

    @Override
    public void createUserInfo() {
        final UserInfo userInfo = userInfoDomainService.create(
                UserInfo.builder()
                        .nickname(new Nickname("FeiOu"))
                        .build()
        );
        domainEventBus.fire(
                CreateUserAccountEvent.builder()
                        .userId(userInfo.getUserId().getUserId())
                        .build()
        );
    }

    @Override
    public UserInfoDTO getUserInfo(Integer userId) {
        UserInfo userInfo = userInfoDomainService.getBasicInfo(new UserId(userId));
        final UserAccountInfoDTO userAccountInfoDTO = accountService.getUserAccountInfo(userId);
        userInfo = userInfoDomainService.linkAccount(
                userInfo,
                Account.builder()
                .userId(new UserId(userAccountInfoDTO.getUserId()))
                .balance(userAccountInfoDTO.getBalance())
                .build()
        );

        return userInfoAssembler.toUserInfoDTO(userInfo);
    }

    @Override
    public void modifyUserInfo(ModifyUserInfoCommand modifyUserInfoCommand) {
        userInfoDomainService.modify(
                UserInfo.builder()
                        .userId(new UserId(modifyUserInfoCommand.getUserId()))
                        .nickname(new Nickname(modifyUserInfoCommand.getNickname()))
                        .build()
        );
    }
}
